// utils/grabOrder/grabOrder.js
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderDetail: [],
    orderId: null,
    time: '',
    distance: null,
    mylat: null,
    mylng: null,
    lat: null,
    lng: null,
    publishId: null,
    project: [],
    check: false,
    isShow: true,
    confirm: "确认",
    show:true,
    sceneImg:""
  },


  isShow: function() {
    this.setData({
      isShow: !this.data.isShow
    })
  },


  /**
   *  确认抢单事件函数
   */
  confirm: function() {
    let that = this;
    if (that.data.check == false) {

      wx.showModal({
        title: '提示',
        content: '请先同意用户协议及隐私声明',
        // showCancel:false,
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../protocol/protocol?protocol=' + 2,
            })
          }
        }
      })
    } else {

      wx.showModal({
        title: '提示',
        content: '确认抢单',
        cancelText: '取消',
        confirmText: '确定',
        confirmColor: '#0bbd79',
        success: function(res) {
          if (res.confirm) {
            wx.request({
              url: 'https://www.xiaozheng8.com/serviceOrder/setStatus/v3',
              method: "post",
              data: {
                status: 4,
                publishId: that.data.publishId,
                userId: wx.getStorageSync("userId"),
                cateId: -1,
              },
              success: function(res) {
                console.log(res)
                that.setData({
                    status: 4,
                    orderId: res.data.data.orderId
                  }),
                  console.log(res)
                console.log(res.data.data.orderId)
                wx.setStorageSync("receiveCheck", true);
                // that.setData({
                //   confirm: "等待发单方确认"
                // })
                wx.redirectTo({
                  url: '../failOrder/failOrder?publishId=' + that.data.publishId + '&distance=' + that.data.distance + "&grab=" + true + "&grabStatus=" + 0,
                })
              },
            })

          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  map: function() {
    let that = this;
    wx.getSetting({
      success: (res) => {
        console.log(res);
        if (!res.authSetting['scope.userLocation'])
          app.openConfirm()
      }, fail(res) {
        console.log(res);
      }
    })
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindById',
      method: "post",
      data: {
        publishId: that.data.publishId,
        userId: wx.getStorageSync("userId"),
      },
      success: function(res) {
      
        // 设置自己位置设置为lat2,发单方位置为lat1
        wx.getLocation({
          success: function(res) {
            wx.navigateTo({
              url: '../map/map?lat1=' + that.data.lat + "&lng1=" + that.data.lng+"&lat2="+res.latitude+"&lng2="+"&lng2="+res.longitude,
            })
          },
        })
       
        // wx.getLocation({ //获取当前经纬度
        //   altitude: true,
        //   type: 'wgs84', //返回可以用于wx.openLocation的经纬度
        //   success: function(res) {
        //     wx.openLocation({ //​使用微信内置地图查看位置。
        //       latitude: that.data.lat, //要去的纬度-地址
        //       longitude: that.data.lng, //要去的经度-地址
        //     })
        //     wx.hideLoading()
        //     console.log("成功")
        //   },fail(res){
        //     wx.hideLoading()
        //   }
        // })

      }

    })
  },

  /**
   * 取消按钮
   */
  cancel: function() {
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 获取当前经纬度
   */
  getAddress: function() {
    /**
     * 获取当前位置
     */
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        that.setData({
          mylat: res.latitude,
          mylng: res.longitude
        })
        // console.log(that.data.lat)
        // console.log(that.data.lng)
      }
    })
  },

  // 点击用户协议
  check: function() {
    this.setData({
      check: !this.data.check
    })
  },
  protocol: function(e) {
    var protocol = e.currentTarget.dataset.protocol;
    wx.navigateTo({
      url: '../protocol/protocol?protocol=' + protocol,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 如果上传了施工前图片，显示施工现场图片
  beforeWorkPic(publishId) {
    var that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/order/img/findByPublishId',
      data: {
        publishId:publishId
      },
      method: 'post',
      success: (res) => {
        console.log(res);
        that.setData({
          sceneImg: res.data.data
        })
      },
      fail: (res) => {
        console.log(res);
      },
      complete: () => { }
    });

  },
  // 预览图片
  imgPreview: function (e) {
    let img = e.currentTarget.dataset.src;
    console.log(img)
    wx.previewImage({
      urls: [img],
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    // wx.getSetting({
    //   success: (res) => {
    //     console.log(res);
    //     if (!res.authSetting['scope.userLocation'])
    //       // app.openConfirm()
    //   }, fail(res) {
    //     console.log(res);
    //   }
    // })
    if (wx.getStorageSync("receiveCheck") == "" || wx.getStorageSync("receiveCheck") == undefined) {

    } else {
      that.setData({
        check: true
      })
    }
    that.getAddress();
    that.setData({
      distance: options.distance
    })
    console.log(options)
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindById',
      method: "post",
      data: {
        publishId: options.publishId,
        userId: wx.getStorageSync("userId"),
        status: 2,
      },
      success: function(res) {
        console.log(res.data.data)
        if (res.data.code == 200) {
          that.setData({
            orderDetail: [res.data.data],
            publishId: res.data.data.publishId,
            lng: res.data.data.lng,
            lat: res.data.data.lat,
            feeItemIds: res.data.data.feeItemIds,
            project: res.data.data.project,
            distance: res.data.data.distance
          })
        }
        // if (options.grab != undefined && options.grabStatus != 2) {
        //   that.setData({
        //     confirm: "等待发单方确认"
        //   })
        // } else if (options.grab != undefined && options.grabStatus == 2) {
        //   that.setData({
        //     confirm: "该订单已被抢"
        //   });
        //   // wx.showNavigationBarLoading()
        //   wx.showToast({
        //     title: '该订单已被抢',
        //     icon:"none",
        //     duration:3000
        //   })
        // }
        /**
         * 费用明细
         */
        let fee = res.data.data.feeItemIds;
        console.log(that.data.distance + "juli")
        that.data.feeItemIds = fee.split(" ");
        that.setData({
          feeItemIds: that.data.feeItemIds,
        })
        let distance = Math.round(that.data.distance / 1000)
        console.log(that.data.distance)
        that.setData({
          distance: distance
        })
      },
    });
    if (this.data.orderDetail.length == 0) {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
    }
    this.beforeWorkPic(options.publishId);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})